<script setup lang="ts">
import { request } from '@/api'
import b64toBlob from 'b64-to-blob'
import {
  closeToast,
  showLoadingToast,
  showToast,
  type ActionSheetAction,
} from 'vant'
import { onMounted, ref } from 'vue'

// 头像修改
const showAvatarSheet = ref(false)
const showAvatarActions = [{ name: '相机' }, { name: '相册' }]
const onSelectAvatar = async (action: ActionSheetAction, index: number) => {
  console.log(action, index)
  if (index == 0) {
    const data = await mk.pickerCamera()
    // console.log('点击了相机')
    onUpdateAvatar(data)
  } else if (index === 1) {
    const data = await mk.pickerPhoto()
    // console.log('点击了相册',data)
    onUpdateAvatar(data)
  }
}
// 点击更新头像
const onUpdateAvatar = async (data: string) => {
  try {
    // 加载动效
    showLoadingToast({
      message: '加载中...',
      forbidClick: true,
      duration: 0,
    })

    // console.log('data数据', data)

    // 转为二进制数据
    const img = b64toBlob(data, 'image/jpeg')
    console.log('img数据', img)

    // 转为FormData格式
    const fd = new FormData() //都非必传
    fd.append('file', img, Date.now() + '.jpeg')

    // 发送请求
    const res = await request.post<MkResponse<{ avatar: string }>>(
      '/member/profile/avatar',
      fd,
    )
    // console.log('res', res.data.result.avatar)

    closeToast()

    profile.value.avatar = res.data.result.avatar

    showToast('修改头像成功')

    // 将信息存储并渲染至页面中
    const user = mk.queryUser()
    user.avatar = res.data.result.avatar
    mk.updateUser(user)
  } catch (error) {
    // console.log('修改头像失败',error)
    showToast('修改头像失败')
  }
}

// 日期修改
const showBirthdayPopup = ref(false)
const birthday = ref(['2003', '02', '17'])
const onConfirmBirthday = (data: any) => {
  console.log('日期选择', data)
  // 将控件选择的生日渲染至页面中
  profile.value.birthday = birthday.value.join('-')
  // 关闭弹层
  showBirthdayPopup.value = false
}

// 地区选择
const showLocationPopup = ref(false)
const areaList = ref()
onMounted(async () => {
  // 获取鸿蒙端数据
  const res = await mk.getAreaColumns()
  // console.log(res)
  areaList.value = res
})
const onConfirmLocation = ({
  selectedValues,
}: {
  selectedValues: number[]
}) => {
  // 便于保存资料的数据传参
  profile.value.provinceCode = selectedValues[0]
  profile.value.cityCode = selectedValues[1]
  profile.value.countyCode = selectedValues[2]

  // 获取控件数据。通过邮编在所有地区中定位
  const province = areaList.value.province_list[selectedValues[0]]
  const city = areaList.value.city_list[selectedValues[1]]
  const county = areaList.value.county_list[selectedValues[2]]
  // 将控件数据渲染至页面中
  profile.value.fullLocation = `${province} ${city} ${county}`
  // console.log(data)
  showLocationPopup.value = false
}

// 数据渲染
const profile = ref<ProfileInfo>({} as ProfileInfo)
onMounted(async () => {
  // 加载动效
  showLoadingToast({
    message: '加载中...',
    forbidClick: true,
    duration: 0,
  })

  const res = await request.get<MkResponse<ProfileInfo>>('/member/profile')
  profile.value = res.data.result
  // 将后端数据渲染生日至页面中
  birthday.value = profile.value.birthday.split('-')

  closeToast()
})

// 职业修改
const showProfessionPopup = ref(false)
const professionColumns = [
  { text: '软件工程师', value: '软件工程师' },
  { text: '医生', value: '医生' },
  { text: '教师', value: '教师' },
  { text: '律师', value: '律师' },
  { text: '会计师', value: '会计师' },
  { text: '销售经理', value: '销售经理' },
  { text: '市场营销专员', value: '市场营销专员' },
  { text: '建筑师', value: '建筑师' },
  { text: '护士', value: '护士' },
  { text: '机械工程师', value: '机械工程师' },
]
const onConfirmProfession = ({
  selectedValues,
}: {
  selectedValues: string[]
}) => {
  // console.log('职业信息',selectedValues[0]);
  profile.value.profession = selectedValues[0]
  showProfessionPopup.value = false
}

// 点击按钮
const loading = ref(false)
const onSubmit = async () => {
  // 加载动效
  loading.value = true

  const res = await request.put<MkResponse<ProfileInfo>>(
    '/member/profile',
    profile.value,
  )
  // 更新至鸿蒙端
  mk.updateUser(res.data.result)
  showToast('保存成功')

  loading.value = false
}
</script>

<template>
  <div class="profile-edit-page">
    <!-- 头像部分 -->
    <div class="avatar">
      <van-image
        round
        width="100"
        height="100"
        class="avatar-img"
        :src="profile.avatar"
        @click="showAvatarSheet = true"
      >
      </van-image>
      <div class="avatar-btn">
        <span @click="showAvatarSheet = true">修改头像</span>
        <!-- 头像控件 -->
        <van-action-sheet
          @select="onSelectAvatar"
          style="padding-bottom: 20px"
          v-model:show="showAvatarSheet"
          :actions="showAvatarActions"
          cancel-text="取消"
          close-on-click-action
        />
      </div>
    </div>

    <!-- 中间表单部分 -->
    <van-cell-group>
      <van-field label="账号" v-model="profile.account" readonly></van-field>
      <van-field
        label="昵称"
        v-model="profile.nickname"
        placeholder="请输入昵称"
      ></van-field>
      <van-cell title="性别" class="gender">
        <van-radio-group :icon-size="16" v-model="profile.gender">
          <van-radio name="男">男</van-radio>
          <van-radio name="女">女</van-radio>
          <van-radio name="未知">未知</van-radio>
        </van-radio-group>
      </van-cell>

      <van-field
        v-model="profile.birthday"
        label="生日"
        readonly
        @click="showBirthdayPopup = true"
        placeholder="请选择日期"
      ></van-field>
      <!-- 日期选择控件 -->
      <van-popup v-model:show="showBirthdayPopup" position="bottom">
        <van-date-picker
          @cancel="showBirthdayPopup = false"
          @confirm="onConfirmBirthday"
          v-model="birthday"
          title="选择日期"
          :min-date="new Date(1949, 10, 1)"
          :max-date="new Date()"
        />
      </van-popup>

      <van-field
        v-model="profile.fullLocation"
        label="所在地"
        readonly
        @click="showLocationPopup = true"
        placeholder="请选择所在地"
      ></van-field>
      <!-- 地区选择控件 -->
      <van-popup v-model:show="showLocationPopup" position="bottom">
        <van-area
          :area-list="areaList"
          @cancel="showLocationPopup = false"
          @confirm="onConfirmLocation"
        />
      </van-popup>

      <van-field
        v-model="profile.profession"
        label="职业"
        @click="showProfessionPopup = true"
        readonly
        placeholder="请选择职业"
      ></van-field>
      <!-- 职业控件 -->
      <van-popup v-model:show="showProfessionPopup" position="bottom">
        <van-picker
          :columns="professionColumns"
          @confirm="onConfirmProfession"
          @cancel="showProfessionPopup = false"
        />
      </van-popup>
    </van-cell-group>

    <div class="submit">
      <van-button
        @click="onSubmit"
        :loading="loading"
        loading-text="加载中..."
        round
        block
        type="primary"
      >
        保存资料
      </van-button>
    </div>
  </div>
</template>

<style lang="css" scoped>
.avatar {
  padding: 30px;
  text-align: center;
  background-color: var(--mk-white);
}

.avatar-img {
  box-shadow: 0 0 5px var(--mk-gray);
}

.avatar-btn {
  color: var(--mk-linear_end);
  margin-top: 10px;
}

.gender ::v-deep(.van-cell__title) {
  width: 100px;
  flex: none;
}

.van-radio-group {
  display: flex;
  justify-content: space-between;
  height: 36px;
  width: 180px;
}

.submit {
  padding: 16px;
}
</style>
